import React, { useEffect, useState } from 'react';
import { Row, Col, Card, Input, Empty, Spin, List, Rate, Space, Typography, Select, Radio } from 'antd';
import { SearchOutlined, UserOutlined, ClockCircleOutlined } from '@ant-design/icons';
import { useDispatch, useSelector } from 'react-redux';
import { setCourses, setFilters, setLoading } from '../../store/courseSlice';
import { courseApi } from '../../api/courseApi';
import { useNavigate } from 'react-router-dom';
import { initialCourses } from '../../store/courseSlice';
import '../../styles/CourseList.css';

// 使用在线默认图片
const defaultCourseImage = 'https://img.alicdn.com/imgextra/i3/O1CN01fTXQ6p1RR7hyvUXCN_!!6000000002117-2-tps-1920-1080.png';

const { Search } = Input;
const { Title, Text } = Typography;
const { Option } = Select;

const CourseList = () => {
  const dispatch = useDispatch();
  const { courses, loading, filters, error } = useSelector(state => state.course);
  const navigate = useNavigate();
  const [categories, setCategories] = useState(['全部']);

  // 加载课程列表
  const loadCourses = async () => {
    try {
      dispatch(setLoading(true));
      // 使用 initialCourses 作为基础数据
      let filteredCourses = [...initialCourses];

      // 搜索过滤
      if (filters?.searchQuery) {
        const query = filters.searchQuery.toLowerCase();
        filteredCourses = filteredCourses.filter(course =>
          course.title.toLowerCase().includes(query) ||
          course.description.toLowerCase().includes(query)
        );
      }

      // 分类过滤
      if (filters?.category && filters.category !== '全部') {
        filteredCourses = filteredCourses.filter(course =>
          course.category === filters.category
        );
      }

      // 排序处理
      if (filters?.sortBy) {
        switch (filters.sortBy) {
          case 'popular':
            filteredCourses.sort((a, b) => b.enrollments - a.enrollments);
            break;
          case 'newest':
            filteredCourses.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
            break;
          case 'rating':
            filteredCourses.sort((a, b) => b.rating - a.rating);
            break;
          default:
            break;
        }
      }

      dispatch(setCourses(filteredCourses));
    } catch (error) {
      console.error('Failed to load courses:', error);
    } finally {
      dispatch(setLoading(false));
    }
  };

  // 加载分类
  const loadCategories = async () => {
    try {
      const categories = [...new Set(initialCourses.map(course => course.category))];
      setCategories(['全部', ...categories]);
    } catch (error) {
      console.error('Failed to load categories:', error);
    }
  };

  useEffect(() => {
    loadCategories();
  }, []);

  useEffect(() => {
    loadCourses();
  }, [filters]);

  // 搜索处理
  const handleSearch = (value) => {
    dispatch(setFilters({ ...filters, searchQuery: value }));
  };

  // 分类处理
  const handleCategoryChange = (value) => {
    dispatch(setFilters({ ...filters, category: value }));
  };

  // 排序处理
  const handleSortChange = (value) => {
    dispatch(setFilters({ ...filters, sortBy: value }));
  };

  if (loading) {
    return <div>加载中...</div>;
  }

  if (error) {
    return <div>错误：{error}</div>;
  }

  return (
    <div className="course-list-container">
      <div className="course-header">
        <Title level={2}>探索课程</Title>
        <Text type="secondary" className="course-subtitle">
          发现适合你的优质课程，开启学习之旅
        </Text>
      </div>

      <div className="course-filters">
        <Row gutter={[16, 16]}>
          <Col xs={24} md={8}>
            <Search
              placeholder="搜索课程"
              onSearch={handleSearch}
              enterButton
              prefix={<SearchOutlined />}
              size="large"
              className="search-input"
            />
          </Col>
          <Col xs={24} md={8}>
            <Select
              placeholder="选择分类"
              onChange={handleCategoryChange}
              value={filters.category}
              size="large"
              style={{ width: '100%' }}
            >
              {categories.map(category => (
                <Option key={category} value={category}>{category}</Option>
              ))}
            </Select>
          </Col>
          <Col xs={24} md={8}>
            <Radio.Group
              onChange={(e) => handleSortChange(e.target.value)}
              value={filters.sortBy}
              className="sort-radio-group"
            >
              <Radio.Button value="newest">最新</Radio.Button>
              <Radio.Button value="popular">最热</Radio.Button>
              <Radio.Button value="rating">好评</Radio.Button>
            </Radio.Group>
          </Col>
        </Row>
      </div>

      <Spin spinning={loading}>
        {courses.length > 0 ? (
          <List
            grid={{
              gutter: 24,
              xs: 1,
              sm: 2,
              md: 3,
              lg: 3,
              xl: 3,
              xxl: 3,
            }}
            dataSource={courses}
            renderItem={course => (
              <List.Item>
                <Card
                  hoverable
                  className="course-card"
                  cover={
                    <div className="course-image-container">
                      <img
                        alt={course.title}
                        src={course.coverImage || defaultCourseImage}
                        className="course-image"
                        onError={(e) => {
                          e.target.onerror = null;
                          e.target.src = defaultCourseImage;
                        }}
                      />
                      <div className="course-category-tag">{course.category}</div>
                    </div>
                  }
                  onClick={() => navigate(`/courses/${course.id}`)}
                >
                  <Card.Meta
                    title={<Title level={4} className="course-title">{course.title}</Title>}
                    description={
                      <div className="course-info">
                        <div className="course-description">
                          {course.description}
                        </div>
                        <Space direction="vertical" size="small" style={{ width: '100%', marginTop: 12 }}>
                          <div className="course-stats">
                            <Space>
                              <UserOutlined />
                              <Text type="secondary">{course.instructor}</Text>
                            </Space>
                            <Space>
                              <ClockCircleOutlined />
                              <Text type="secondary">{course.duration}</Text>
                            </Space>
                          </div>
                          <div className="course-footer">
                            <div className="course-rating-wrapper">
                              <Rate disabled defaultValue={course.rating} className="course-rating" />
                              <Text type="secondary" className="course-enrollments">
                                ({course.enrollments}人已报名)
                              </Text>
                            </div>
                            <Text type="danger" strong className="course-price">
                              ¥{course.price}
                            </Text>
                          </div>
                        </Space>
                      </div>
                    }
                  />
                </Card>
              </List.Item>
            )}
          />
        ) : (
          <Empty
            description="暂无课程"
            image={Empty.PRESENTED_IMAGE_SIMPLE}
          />
        )}
      </Spin>
    </div>
  );
};

export default CourseList; 